package com.lh.lepay.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.lh.lepay.utils.HttpStatus;
import com.lh.lepay.utils.ResponseData;
import com.lh.lepay.utils.ServerInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

@RestController
@CrossOrigin("*")
@Slf4j
@Tag(name = "测试接口")
@RequiredArgsConstructor
@RequestMapping("cs")
public class TestController {
    private LineCaptcha lineCaptcha;

    @GetMapping("/test")
    @Operation(description = "测试hello world")
    @PreAuthorize("hasAnyAuthority('sys:info:test')")
    //@ApiResponse(responseCode = "200", description = "成功响应", content = @Content(schema = @Schema(type = "string")))
    public String test() {
        return "你好， 世界";
    }


    @GetMapping("/code")
    @Operation(description = "简单验证码")
    //@ApiResponse(responseCode = "200", description = "成功响应", content = @Content(schema = @Schema(type = "string")))
    public String getCaptchaBase64() throws Exception {
        // 创建验证码对象
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(100, 30,4,20);
        // 获取验证码文字
        String code = captcha.getCode();
        // 获取验证码图片
        BufferedImage image = captcha.getImage();

        // 使用 ByteArrayOutputStream 转换 BufferedImage 对象为字节数组
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(image, "png", os);
        byte[] bytes = os.toByteArray();

        // 将字节数组转换为 Base64 编码字符串
        String base64Image = Base64.encode(bytes);

        // 关闭输出流
        os.close();

        // 构建返回的数据结构
        String result = StrUtil.format("{\"code\":\"{}\",\"image\":\"data:image/png;base64,{}\"}", code, base64Image);
        return result;
    }

    @GetMapping("/server")
    @Operation(description = "获取服务器信息")
    public ResponseData getInfo() throws Exception
    {
        ServerInfo server = new ServerInfo();
        server.copyInfo();
        log.info(server.getJvm().getName());
        return new ResponseData(HttpStatus.SUCCESS, server);
    }

    @PostMapping("/sendSession")
    public String sendUsernameSession(HttpSession session){
        session.setAttribute("username","admin");
//        log.info(session.toString());
        return "sendSession is ok";
    }

    @PostMapping("/getSession")
    public String getUsernameSession(HttpSession session){
        String username = (String) session.getAttribute("username");
        log.info("当前用户信息：" + username);
        return "getSession is ok" + "当前用户信息：" + username;
    }
}